/**
 * @author:cloud.lg
 * @date:2021.7.26
 * @description: 报关单管理
 */
<template>
  <div class="tc-username-index fiexBox">
    <section class="tavle-content">
      <!-- 头部 -->
      <el-header height="auto">
        <!-- 搜索 -->
        <el-form :inline="true" :model="formData" class="demo-form-inline heard-search" @submit.native.prevent>
          <el-form-item label="搜索:">
            <el-input v-model="formData.searchValue" @keyup.enter.native="search" placeholder="请输入">
              <el-tooltip slot="append" class="item l" effect="dark" content="输入【用户编码】【账号】【用户名】模糊搜索" placement="top">
                <el-button icon="el-icon-warning"></el-button>
              </el-tooltip>
            </el-input>
          </el-form-item>
          <el-form-item class="content-box" label="部门:">
            <el-cascader
              v-icon-hide
              :show-all-levels="true"
              filterable
              v-model="formData.deptId"
              :options="deptList"
              :props="{ checkStrictly: true, value: 'id', label: 'label', emitPath: false}"
              clearable>
              <template slot-scope="{ node, data }">
                <span>{{ data.label }}</span>
                <span v-if="!node.isLeaf"> ({{ data.children.length }}) </span>
              </template>
            </el-cascader>
          </el-form-item>
          <el-form-item label="角色:">
            <el-select v-model="formData.roleId" clearable filterable placeholder="请选择">
              <el-option v-for="(item, index) in roleList" :key="index" :label="item.roleName" :value="item.roleId"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="用户状态:">
            <el-select v-model="formData.status" clearable placeholder="请选择">
              <el-option label="停用" :value="1"></el-option>
              <el-option label="启用" :value="0"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-tooltip class="item" effect="dark" content="搜索" placement="top">
              <el-button class="searchbtn" icon="el-icon-search" type="primary" @click="search"></el-button>
            </el-tooltip>
            <el-tooltip class="item" effect="dark" content="重置" placement="top">
              <el-button class="resetBtn" icon="el-icon-refresh-left" @click="search('reset')"></el-button>
            </el-tooltip>
          </el-form-item>
        </el-form>
        <!-- 按钮 -->
        <div class="main_search_button">
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(1)">一般贸易</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(201)">9710/9810跨境电商</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(2)">采购-广州</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(3)">采购-佛山</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(102)">采购-中山</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(5)">采购-东莞</el-button>
          <el-button type="primary" size="mini" icon="el-icon-plus" @click="searchButton(4)">采购-烟台</el-button>
        </div>
      </el-header>
      <!-- 表格 -->
      <el-main>
        <section ref="main_table" class="row-table">
          <el-table
            class="rowtable"
            :data="tableData"
            highlight-current-row
            @row-dblclick="tableClick"
            v-loading="isShowLoading"
            stripe
            :max-height="tableHeight"
            style="width: 100%">
            <el-table-column
              v-if="item.isShow"
              v-for="(item, index) in tableHeaderData"
              :key="index"
              :prop="item.prop"
              :width="item.width"
              align="left"
              :show-overflow-tooltip="true"
              :label="item.label">
              <template slot-scope="scope">
                <span v-if="item.propParent && scope.row[item.propParent]">{{scope.row[item.propParent][item.prop]}}</span>
                <span v-else-if="item.type === 'time'">{{ dateToString(scope.row[item.prop]) }}</span>
                <span v-else-if="item.prop === 'containers'">{{ scope.row[item.prop].length > 0 ? scope.row[item.prop][0].code : '-'}}</span>
                <span v-else-if="item.prop === 'manifestDataJson'">{{ getManifestDataJson(scope.row) }}</span>
                <span v-else-if="item.prop === 'makeType'">{{getMakeTypeStr(scope.row[item.prop])}}</span>
                <span v-else-if="scope.row[item.prop]">{{scope.row[item.prop]}}</span>
                <span v-else>-</span>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              label="操作"
              align="left"
              width="150">
              <template slot="header" slot-scope="scope">
                <div>操作<table-heard-option :tableHeaderData="tableHeaderData"></table-heard-option></div>
              </template>
              <template slot-scope="scope">
                <el-button  type="text" size="medium" class="p3" @click="addEdit('edit', scope.row)">编辑</el-button>
                <el-button  type="text" size="medium" class="p3" @click="addEdit('delete', scope.row)">删除</el-button>
                <!-- <el-dropdown trigger="click" @command="dropdownCommand">
                  <span class="el-dropdown-link left-shu">
                    <el-button  type="text" size="medium" class="p3"><i class="iconfont icongengduo1"></i> 更多<i class="iconfont iconarrow-down"></i></el-button>
                  </span>
                  <el-dropdown-menu slot="dropdown">
                    <el-dropdown-item :command="{key: 0, row: scope.row}">启用</el-dropdown-item>
                    <el-dropdown-item :command="{key: 1, row: scope.row}">停用</el-dropdown-item>
                    <el-dropdown-item :command="{key: 'reset', row: scope.row}">重置密码</el-dropdown-item>
                  </el-dropdown-menu>
                </el-dropdown> -->
              </template>
            </el-table-column>
          </el-table>
        </section>
      </el-main>

      <!-- 分页 -->
      <el-footer height="auto">
        <div class="block-pagination r clearfix">
          <el-pagination
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="formData.page"
            :page-sizes="[20, 50, 100, 200]"
            :page-size="formData.limit"
            layout="total, prev, pager, next, sizes, jumper"
            :total="totalCont">
          </el-pagination>
        </div>
      </el-footer>
    </section>

    <!-- 添加弹窗 -->
    <el-dialog :title="makeForm.title" width="500px" :visible.sync="makeForm.dialog" @open="initMakeForm">
      <el-form :model="makeForm"  @submit.native.prevent class="input-auto">
        <el-form-item label="进出口" label-width="100px" v-show="makeForm.isIoType">
          <el-select v-model="makeForm.ioType" placeholder="请选择">
            <el-option label="出口" :value="1"></el-option>
            <el-option label="进口" :value="2"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="模板(可选)" label-width="100px">
          <el-select v-model="makeForm.tpl" placeholder="请选择">
            <el-option label="请选择" value=""></el-option>
            <el-option :label="item.name" :value="item.id" v-for="(item, index) in tplOptions" :key="index"></el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer tc">
        <el-button type="primary" @click="startMake">开始制单</el-button>
      </div>
    </el-dialog>
    <!-- 弹窗表单 -->
    <prop-form :propOptions="propOptions" :propformHeard="propformHeard" :propSubmit="propSubmit" :propSelect="propSelect"></prop-form>
  </div>
</template>

<script>
import { mapState,mapMutations } from 'vuex';
import { getDeclMakeList, createDeclMake, delMake } from '@/axios/business/decl';
import { dateToString } from '@/utils/util';
import { maketplAll } from '@/axios/api';
import elementResizeDetectorMaker from "element-resize-detector";
import Sortable from 'sortablejs';

var viewer = null;
export default {
  name: 'username',
  data () {
    return {
      formData: {
        page: 1,
        limit: 20,
        _t: 1628476582013
      },
      totalCont: 0,
      isShowLoading: false,
      roleList: [],
      deptList: [],
      tableHeight: 0,
      tableHeaderData: [
        { label: '制单日期', prop: 'makeTime', type:'time', width: '100', isShow: true },
        { label: '所属主体', prop: 'mainbodyName', width: '200', isShow: true },
        { label: '截关时间/备注', prop: 'remark', width: '190', isShow: true },
        { label: '代理客户', prop: 'customerName', width: '100', isShow: true },
        { label: '境内收发货人', prop: 'entName', propParent: 'make', width: '242', isShow: true },
        { label: '第一项品名', prop: 'firstGoodsName', propParent: 'make', width: '110', isShow: true },
        { label: '项数', prop: 'goodsItemNum', propParent: 'make', width: '60', isShow: true },
        { label: '申报金额', prop: 'goodsTotalMoney', propParent: 'make', width: '80', isShow: true },
        { label: '柜号', prop: 'containers', width: '135', isShow: true },
        { label: '提运单号', prop: 'drawNumber', propParent: 'make', width: '135', isShow: true },
        { label: '状态', prop: 'customsTips', width: '145', isShow: true },
        { label: '监管方式', prop: 'makeType', width: '145', isShow: true },
        { label: '舱单状态', prop: 'manifestDataJson', width: '145', isShow: true },
        { label: '舱单状态', prop: 'manifestDataJson', width: '145', isShow: true },
        { label: '预录入编号', prop: 'customsSeqno', width: '167', isShow: true },
        { label: '报关单号', prop: 'customsCode', width: '163', isShow: true },
        { label: '海关回执', prop: 'customsTips', width: '135', isShow: true }
      ],
      tableData: [],
      // 制单页面
      makeForm: {
        dialog: false,
        type: 1,
        ioType: 1,
        declType: 0,
        decType: 1,
        customerId: 0,
        nowDate: dateToString(new Date(),"yyyy-mm-dd"),
        tpl: '',
        isIoType: true
      },
      tplOptions: [],
      // 报关单配置
      customsOption: {
        // rule 是否必填默认非必填
        formRules: {
          customerId: true,
          ioCustomsId: true
        },
        // disabled 是否禁用默认启用
        formDisabled: {
          ioType: true,
          customsCode: true,
          customsSeqno: true,
          passDate: true,
          delegationCode: true,
          'z-validTime': true,
          'z-ieDate': true
        },
        // 初始化数据
        formInitData: {
          ioType: 1,
          customsCode: '222',
        },
      },
      // 弹窗表单
      propOptions: {
        title: '添加',
        isShow: false,
        buttons: [
          { type: 'save', name: '保存' }
        ]
      },
      propformHeard: [
        { colSpan: 24, type: 'input', key: 'order', value: '', isRequired: true, disabled: false, label: '所属主体：', labelWidth: '90px' },
        { colSpan: 24, type: 'input', key: 'order2', value: '', isRequired: true, disabled: false, label: '所属商户：', labelWidth: '90px' },
        { colSpan: 24, type: 'select', key: 'order3', value: '', isRequired: true, disabled: false, label: '下拉选择：', labelWidth: '90px', option: [{name: '张三', id: 1, code: '001'}]}
      ]
    }
  },
  computed:{
    ...mapState([
      'editableTabs',
      'editableTabsValue',
      'partnerData',
      'menuData',
      'isSystem'
    ])
  },
  watch: {
  },
  components: {
    tableHeardOption: resolve => {require(['@/components/tools/tableHeardOption/index'], resolve)}, // 表头选择器
    propForm: resolve => {require(['@/components/tools/propForm/index'], resolve)}, // 弹出表单
  },
  mounted() {
    document.body.ondrop = function (event) {
      event.preventDefault();
      event.stopPropagation();
     };
    this.rowDrop()
    this.columnDrop()
    this.watchSize();
    this.init()
  },
  created(){
    this.getTableList()
  },
  methods: {
    ...mapMutations([
      'SAVE_TOKEN',
      'SAVE_EDITABLETABS'
    ]),
    init() {
    },
    /**
     * @method 监听表格流体高度
     */
    watchSize() {
      const _this = this;
      var erd = elementResizeDetectorMaker();
      erd.listenTo(this.$refs.main_table, (element) => {
        var width = element.offsetWidth;
        var height = element.offsetHeight;
        _this.$nextTick(() => { // 这里填写监听改变后的操作
          _this.tableHeight = height
        });
      });
    },
    async getTableList() {
      this.isShowLoading = true
      let data = await getDeclMakeList(this.formData)
      if (data.code === 0) {
        this.tableData = data.data
        this.totalCont = data.count
      }
      this.isShowLoading = false
    },
    search(param) {
      if (param === 'reset') {
        this.formData.searchValue = ''
        this.formData.roleId = ''
        this.formData.status = ''
      }
      this.getTableList()
    },
    /**
    * @method 新增/编辑
    * @param {string} type add 新增 edit 编辑
    */
    addEdit(type, params) {
      if (type === 'edit') {
        let item = {
          id: params.id,
          query: {
            makeType: params.makeType,
            id: params.id,
            tpl: ''
          }
        }
        item.viewUri = '/business/decl/make'
        if(params.makeType == 1) { // 一般贸易
          item.title = `一般贸易(${item.query.id})`
        } else if (params.makeType == 201) {
          item.title = `跨境电商(${item.query.id})`
        } else if (params.makeType == 2) {
          item.title = `广州采购(${item.query.id})`
        } else if (params.makeType == 3) {
          item.title = `佛山采购(${item.query.id})`
        } else if (params.makeType == 102) {
          item.title = `中山采购(${item.query.id})`
        } else if (params.makeType == 5) {
          item.title = `东莞采购(${item.query.id})`
        } else if (params.makeType == 4) {
          item.title = `烟台采购(${item.query.id})`
        }
        this.$router.push({
          path: item.viewUri,
          query: item.query
        })
        item.menuId = item.query.id
        this.SAVE_EDITABLETABS(item)
      } else if (type === 'delete') {
        this.$confirm('确定要删除该报关单?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          delMake({id: params.make.id}).then((res) => {
            if (res.code === 0) {
              this.$message({
                type: 'success',
                message: '操作成功'
              })
              this.getTableList()
            }
          })
        }).catch(() => {})
      }
    },
    /**
    * @method 头部按钮点击
    * @param {string} type 
    */
    searchButton(type){
      this.makeForm.type = type
      this.makeForm.isIoType = false
      // 获取制单模板
      maketplAll({
        type: this.makeForm.type
      }).then(res => {
        if (res.code === 0) {
          this.tplOptions = res.data
        }
      })
      switch (type) {
        case 1: //一般贸易
        this.makeForm.title = '准备制单 - 一般贸易'
        this.makeForm.isIoType = true
        break
        case 201: // 跨境电商
        this.makeForm.title = '准备制单 - 跨境电商'
        break
        case 2: // 广州采购
        this.makeForm.title = '准备制单 - 广州采购'
        break
        case 3: // 佛山采购
        this.makeForm.title = '准备制单 - 佛山采购'
        break
        case 102: // 中山采购
        this.makeForm.title = '准备制单 - 中山采购'
        break
        case 5: // 东莞采购
        this.makeForm.title = '准备制单 - 东莞采购'
        break
        case 4: // 烟台采购
        this.makeForm.title = '准备制单 - 烟台采购'
        break
      }
      this.makeForm.dialog = true
    },
    // 打开制单弹窗
    initMakeForm() {
      this.makeForm.ioType = 1
      this.makeForm.tpl = ''
    },
    // 开始制单
    startMake() {
      let item = {
        id: '',
        query: {
          id: '',
          makeType: this.makeForm.type,
          tpl: this.makeForm.tpl
        }
      }
      createDeclMake({
        nowDate: this.makeForm.nowDate,
        customerId: this.makeForm.customerId,
        ioType: this.makeForm.ioType,
        declType: this.makeForm.declType,
        decType: this.makeForm.decType
      }).then(res => {
        if (res.code === 0) {
          item.id = res.data
          item.query.id = res.data
          item.query.tpl = this.makeForm.tpl
          item.viewUri = '/business/decl/make'
          switch (this.makeForm.type) {
            case 1: //一般贸易
            item.title = `一般贸易(${item.query.id})`
            break
            case 201: //跨境电商
            item.title = `跨境电商(${item.query.id})`
            break
            case 2: //一般贸易
            item.title = `广州采购(${item.query.id})`
            break
            case 3:
            item.title = `佛山采购(${item.query.id})`
            break
            case 102:
            item.title = `中山采购(${item.query.id})`
            break
            case 5:
            item.title = `东莞采购(${item.query.id})`
            break
            case 4:
            item.title = `烟台采购(${item.query.id})`
            break
          }
          this.$router.push({
            path: item.viewUri,
            query: item.query,
            makeType: this.makeForm.type
          })
          item.menuId = item.query.id
          this.SAVE_EDITABLETABS(item)
          this.makeForm.dialog = false
        }
      })
    },
    handleSizeChange(val) {
      this.formData.page = 1
      this.formData.limit = val
      this.getTableList()
    },
    handleCurrentChange(val) {
      this.formData.page = val
      this.getTableList()
    },
    /**
     * @method 下拉菜单点击
     * @param {string} param 1 启用 3 停用 reset 重置密码
     */
    dropdownCommand(param) {
    },
    /**
     * @method 表格点击
     */
    tableClick(row, column) {
      this.addEdit('edit', row)
    },
    /**
     * 报关单点击回调
     */
    buttonClick(type, data) {
      console.log(type)
      console.log(data)
    },
    getManifestDataJson(d) {
      if (!d.make) {
        return
      }
      var mfshipBillSavedStyle = '<a style="background:#999;color:#FFF;padding:3px">已录</a>';
      var mfshipBillSavedStylePass = '<a style="background:green;color:#FFF;padding:3px">放行</a>';
      var s = d.make.manifestDataJson != null ? d.make.manifestDataJson.status : '-',
          sn = d.mfshipBillShipAgencyName === null ? '' : ' - '+d.mfshipBillShipAgencyName;
      if(d.mfshipBillStatus != null){
          //放行
          if(d.mfshipBillStatus === 100){
              return s === '-' ? mfshipBillSavedStylePass+sn : s+' - '+mfshipBillSavedStylePass+sn;
          }
          return s === '-' ? mfshipBillSavedStyle+sn : s+' - '+mfshipBillSavedStyle+sn;
      }
      return s;
    },
    getMakeTypeStr(type) {
      switch(type){
        case 1:
          return '一般贸易';
        case 2:
        case 101:
          return '广州采购';
        case 3:
          return '佛山采购';
        case 4:
          return '烟台采购';
        case 102:
          return '中山采购';
        case 5:    
        case 103:
          return '东莞采购';
        case 201:
          return '电商9710';
        case 202:
          return '电商9810';
      }
    },
    // 时间格式
    dateToString(time) {
      return dateToString(time, 'yyyy-mm-dd')
    },
     //行拖拽
    rowDrop() {
      const tbody = document.querySelector('.el-table__body-wrapper tbody')
      const _this = this
      Sortable.create(tbody, {
        onEnd({ newIndex, oldIndex }) {
          const currRow = _this.tableData.splice(oldIndex, 1)[0]
          _this.tableData.splice(newIndex, 0, currRow)
        }
      })
    },
    //列拖拽
    columnDrop() {
      const wrapperTr = document.querySelector('.el-table__header-wrapper tr')
      this.sortable = Sortable.create(wrapperTr, {
        animation: 180,
        delay: 0,
        onEnd: evt => {
          this.isShowLoading = true
          let data = JSON.parse(JSON.stringify(this.tableHeaderData))
          swapArr(data, evt.oldIndex, evt.newIndex)
          this.tableHeaderData = []
          this.$nextTick(() => {
            this.tableHeaderData = data
            this.isShowLoading = false
          })
        }
      })
      function swapArr(arr, index1, index2) {
          arr[index1] = arr.splice(index2, 1, arr[index1])[0];
          return arr;
      }
    },
    // 弹窗表单按钮点击
    propSubmit(option) {
      console.log(option)
      this.propOptions.isShow = false
    },
    // 弹窗下拉选择
    propSelect(option) {
      console.log(option)
    }
  }
};
</script>

<style lang="scss">
@import "./index.scss";
</style>